package com.ruoyi.framework.web.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.shiro.service.LoginService;
import com.ruoyi.framework.web.service.PermissionService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.mapper.UserMapper;

@Component
public class BaseAction {
	
	@Autowired
	private UserMapper userMapper;

	@Autowired
    private RedisUtil redisUtil;
	
	@Autowired
    private PermissionService permission;

	/**
	 * 公共信息展示；
	 * @param msg
	 * @return
	 */
	protected ModelAndView message(String msg){
		ModelAndView mv=new ModelAndView("common/msg");
		mv.addObject("msg", msg);
		return mv;
	}
	
	/**
	 * 获取渠道商为cpa的渠道列表；
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<String> channelCPA(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.CHANNEL_CPA_CIDS);
		if(obj!=null){
			List<String> list = (List<String>)obj;
			if(list.size() > 0){
				return list;
			}
			return null;
		}
		return null;
	}
	
	/**
	 * 获取渠道商为cps的渠道列表；
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<String> channelCPS(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.CHANNEL_CPS_CIDS);
		if(obj!=null){
			List<String> list = (List<String>)obj;
			if(list.size() > 0){
				return list;
			}
			return null;
		}
		return null;
	}
	
	/**
	 * 获取渠道商所有类型的cid；
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<String> channelAllCid(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.ALL_CIDS);
		if(obj!=null){
			List<String> list = (List<String>)obj;
			if(list.size() > 0){
				return list;
			}
			return null;
		}
		return null;
	}
	
	/**
	 * 获取渠道商为公会的渠道列表；
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<String> channelGuild(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.CHANNEL_GUILD_CIDS);
		if(obj!=null){
			List<String> list = (List<String>)obj;
			if(list.size() > 0){
				return list;				
			}
			return null;
		}
		return null;
	}
	
	/**
	 * 获取推广渠道列表
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<String> promoterChannel(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.PROMOTER_CHANNEL_IDS);
		if(obj!=null){
			List<String> list = (List<String>)obj;
			if(list.size() > 0){
				return list;				
			}
			return null;
		}
		return null;
	}
	
	
	
//	/**
//	 * 当前用户推广的渠道列表，用户渠道商查看自己的渠道数据；
//	 * @param request
//	 * @return
//	 */
//	@SuppressWarnings("unchecked")
//	protected List<String> currentCids(HttpServletRequest request){
//		Object obj=request.getSession().getAttribute(LoginService.CURRENT_CIDS);
//		if(obj!=null){
//			return (List<String>)obj;
//		}
//		return null;
//	}
//	
//	/**
//	 * 当前用户推广的渠道列表，用户渠道商查看自己的渠道数据；
//	 * @param request
//	 * @return
//	 */
//	@SuppressWarnings("unchecked")
//	protected List<String> currentGhCids(HttpServletRequest request){
//		Object obj=request.getSession().getAttribute(LoginService.CURRENT_GH_CIDS);
//		if(obj!=null){
//			return (List<String>)obj;
//		}else{
//			List<String> cids=new ArrayList<String>();
//			cids.add("NOTHISCID");
//			return cids;
//		}
//	}
	
	
	/**
	 * 获取下级的用户ID列表；用于各个组长查询下属组员的数据；
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<Long> subUids(){
		Object obj=redisUtil.get(getLoginName()+LoginService.CURRENT_SUB_UIDS);
		if(obj!=null){
			return (List<Long>)obj;
		}
		return null;
	}
	
	/**
	 * 用户运营组员获取自己运营得游戏列表；
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<Integer> yyGameIds(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.YY_GAMES);
		if(obj!=null){
			return (List<Integer>)obj;
		}
		return null;
	}
	
	/**
	 * 获取下级的渠道号列表；
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<String> subCids(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.CURRENT_SUB_CIDS);
		if(obj!=null){
			return (List<String>)obj;
		}
		return null;
	}
	
	
	/**
	 * 获取当前推广员的渠道号
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<String> promoterCids(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.PROMOTER_CIDS);
		if(obj!=null){
			return (List<String>)obj;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	protected List<String> pjCids(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.PJ_CIDS);
		if(obj!=null){
			return (List<String>)obj;
		}
		return null;
	}
	
	/**
	 * 获取当前运营人员的游戏
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Integer> operationGameId(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(LoginService.YY_GAMES);
		if ( obj != null ) {
			return (List<Integer>) obj;
		}
		return null;
	}
	
	/**
	 * 获取当前登录用户的用户ID
	 * @param request
	 * @return
	 */
	protected Integer currentUserId(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.CURRENT_USER_ID);
		if(obj!=null){
			return ((Number)obj).intValue();
		}
		return null;
	}
	
	/**
	 * 获取当前登录用户的用户昵称
	 * @param request
	 * @return
	 */
	protected String currentUserName(HttpServletRequest request){
		Object obj = request.getSession().getAttribute("name");
		if(obj!=null){
			return obj.toString();
		}
		return null;
	}
	
	/**
	 * 获取当前登录用户的用户账号
	 * @param request
	 * @return
	 */
	protected String currUserName(HttpServletRequest request){
		Object obj = request.getSession().getAttribute("userName");
		if(obj!=null){
			return obj.toString();
		}
		return null;
	}
	
	/**
	 * 获取当前用户推广的游戏列表；一般用于CP商和游戏厂商；
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<Integer> currentGameIds(HttpServletRequest request){
		Object obj=request.getSession().getAttribute(LoginService.CURRENT_GAME_IDS);
		if(obj!=null){
			return (List<Integer>)obj;
		}
		return null;
	}
	
	/**
	 * 通用方法，获取推广员；
	 * @param request
	 * @return
	 */
	public List<User> generateQueryPromoters(HttpServletRequest request){
		
//		Integer promoterId=null;
		List<Long> promoterIds=null;
		List<Integer> gameIds=null;
		
		//公会组员和商务组员只能查看自己的渠道
//		if(permission.isAnyRoles("ROLE_GH") || permission.isAnyRoles("ROLE_SW")){
//			promoterId=this.currentUserId(request);
//			
//		}
		if (permission.isAnyRoles("ROLE_HEZUO_USER")) {  //第三方合作用户
			Long promoterId = ShiroUtils.getSysUser().getUserId();
			promoterIds = new ArrayList<Long>();
			promoterIds.add(promoterId);
			return userMapper.findUserByUserIds(promoterIds);
		} else if(permission.isAnyRoles("ROLE_GH,ROLE_SW,ROLE_GHZZ,ROLE_SWZZ")){ //公会组组长和商务组长只能查看自己和组员的渠道
				promoterIds = this.subUids();
			return userMapper.findUserByUserIds(promoterIds);
		} else if(permission.isAnyRoles("ROLE_YY")){  //运营组员可以查看自己推广的游戏
			gameIds=this.yyGameIds(request);
			return userMapper.findUserByGameIds(gameIds);
		} else if (permission.isAnyRoles("ROLE_YYZZ") || permission.isAnyRoles("ROLE_ADMIN")) {
			return userMapper.findUserByRoleKeys("'ROLE_SW,ROLE_SWZZ,ROLE_GH,ROLE_GHZZ'");
		}
		
		return new ArrayList<User>();
		//运营组长不受游戏、推广员限制
//		if(permission.isAnyRoles("ROLE_YYZZ")){
//			promoterIds=null;
//			gameIds=null;
//			promoterId=null;
//		}
//		return userService.findPromoters(promoterId,promoterIds,gameIds);
	}
	
	
	/**
	 * 根据时间标签产生查询参数；
	 * @param flag 时间标签
	 * @return Map里面包含两个key,分别为:startDate和endDate;什意思，你懂的;
	 */
	protected Map<String,Object> generateQueryDateByFlag(String flag){
		
		String startDate=null;
		String endDate=null;
		
		if (!StringUtils.isEmpty(flag)) {
			
			//最近7天
			if("last7days".equals(flag)){
				startDate = DateUtil.format(DateUtil.getLastNday(-7), "yyyy-MM-dd");
			}
			
			//最近15天
			if("last15days".equals(flag)){
				startDate = DateUtil.format(DateUtil.getLastNday(-15), "yyyy-MM-dd");
			}
			
			//最近30天
			if("last30days".equals(flag)){
				startDate = DateUtil.format(DateUtil.getLastNday(-30), "yyyy-MM-dd");
			}
			
			//本周
			if("current_week".equals(flag)){
				startDate = DateUtil.format(DateUtil.getFirstDayOfWeek(), "yyyy-MM-dd");
			}
			
			//本月
			if("current_month".equals(flag)){
				startDate = DateUtil.format(DateUtil.getStartDateOfCurrentMonth(), "yyyy-MM-dd");
			}
			//昨天
			if("current_yesterday".equals(flag)){
				startDate = DateUtil.format(DateUtil.getYestoday(), "yyyy-MM-dd");
			}
			//今天
			if("current_now".equals(flag)){
				startDate = DateUtil.format(new Date(), "yyyy-MM-dd");
			}
			
			endDate =  DateUtil.format(new Date(), "yyyy-MM-dd");
			
		}else{
			
			startDate = DateUtil.format(DateUtil.getLastNday(-7), "yyyy-MM-dd");
			endDate =  DateUtil.format(new Date(), "yyyy-MM-dd");
		}
		
		Map<String,Object> queryMap=new HashMap<String,Object>();
		queryMap.put("startDate", startDate);
		queryMap.put("endDate", endDate);
		return queryMap;
		
	}

	//http://www.cnblogs.com/fsjohnhuang/p/4081445.html
	public int refCache() throws IOException, InterruptedException {
		String shpath ="sh /cron/monitor/mem_cache.sh";   //程序路径
	    Process process = Runtime.getRuntime().exec(shpath);
	    
	    InputStream stderr = process.getErrorStream();  
	    InputStreamReader isr = new InputStreamReader(stderr);  
	    BufferedReader br = new BufferedReader(isr);  
	    String line = null;  
	    System.out.println("<ERROR>");  
	    while ((line = br.readLine()) != null)  
	        System.out.println(line);  
	    System.out.println("</ERROR>");
	    
		int exitVal = process.waitFor();
		return exitVal;
	}
	
	public User getSysUser()
    {
        return ShiroUtils.getSysUser();
    }

    public void setSysUser(User user)
    {
        ShiroUtils.setSysUser(user);
    }

    public Long getUserId()
    {
        return getSysUser().getUserId();
    }

    public String getLoginName()
    {
        return getSysUser().getLoginName();
    }

}
